# coding=utf-8
__author__ = 'liubin'

import os.path
from flask import url_for
from flask.ext.admin import form
from flask.ext.admin.contrib.sqla import ModelView
from jinja2 import Markup

from project import app
from project.tools import namegen_uuid

class ImageView(ModelView):
    """
    flask-admin 用的用来上传图片的管理视图
    """
    def _list_thumbnail(view, context, model, name):
        """
            生成一览所用的图片控件
        :param view:
        :param context:
        :param model:
        :param name:
        :return:
        """
        if not model.image:
            return ''
        path = os.path.join(app.config['UPLOAD_DIRECTORY'], model.image).replace('\\', '/')
        return Markup('<img src="%s">' % url_for('static',
                                                 filename=form.thumbgen_filename(path)))
    #一览所用的图片列
    column_formatters = {
        'image': _list_thumbnail
    }

    # Alternative way to contribute field is to override it completely.
    # In this case, Flask-Admin won't attempt to merge various parameters for the field.
    #form 所用图片控件
    form_extra_fields = {
        'image': form.ImageUploadField('Image',
                                      base_path=app.config['UPLOAD_PATH'],
                                      url_relative_path = app.config['UPLOAD_DIRECTORY'] + '/',
                                      thumbnail_size=(100, 100, True),
                                      namegen=namegen_uuid)
                                      #validators=[InputRequired()])
    }